﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace BCC.Common.AuthorizationUtils
{
    public static class AuthorizationUtils
    {
        //供身份验证后存储身份信息使用
        public static string authorization = "";

        public static string HttpAuthorizationPost(string url, object body)
        {

            //把用户传过来的数据转成“UTF-8”的字节流
            Encoding encoding = Encoding.UTF8;
            //先根据用户请求的uri构造请求地址
            //创建Web访问对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            // request.Accept = "application/json";
            request.ContentType = "application/json; charset=UTF-8";
            request.Headers["Accept-Encoding"] = "gzip, deflate";
            if (authorization != null)
            {
                request.Headers["Authorization"] = "Bearer " + authorization;
            }

            request.AutomaticDecompression = DecompressionMethods.GZip;

            var postBody = JsonConvert.SerializeObject(body);
            byte[] buffer = encoding.GetBytes(postBody);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            //通过Web访问对象获取响应内容
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            }
        }

        public static string HttpAuthorizationGet(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);    //创建一个请求示例 
                request.ContentType = "application/json";
                if (authorization != null)
                {
                    request.Headers["Authorization"] = "Bearer " + authorization; //添加头
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();  //获取响应，即发送请求
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
